package com.epoch.zuul.auth.service.impl;

import bean.response.ResponseBean;
import bean.response.ResultEnum;
import com.epoch.zuul.auth.dao.AuthDao;
import com.epoch.zuul.auth.dao.AuthRoleDao;
import com.epoch.zuul.auth.dao.CsRoleDao;
import com.epoch.zuul.auth.dao.RolesDao;
import com.epoch.zuul.auth.role.Auth;
import com.epoch.zuul.auth.role.Roles;
import com.epoch.zuul.auth.service.AuthRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.ResultInfoUtil;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Seven
 * @date 2021/12/4
 */
@Service
public class AuthRoleServiceImpl implements AuthRoleService {

    @Autowired
    private RolesDao rolesDao;

    @Autowired
    private AuthRoleDao authRoleDao;

    @Autowired
    private AuthDao authDao;

    @Autowired
    private CsRoleDao csRoleDao;

    /**
     * 根据角色名称获取权限列表
     * @param
     * @return
     */
    @Override
    public ResponseBean getAuthListByRoleName() {
        //获取角色Id
        Integer roleId = rolesDao.getRoleByRoleName("学生").getRoleId();
        if (roleId == null){
            return ResultInfoUtil.buildError(ResultEnum.BAD_REQUEST, "获取权限列表失败，该角色不存在");
        }
        //存贮角色拥有的权限
        List<Auth> result = getAuthListByRoleId(roleId);
        return ResultInfoUtil.buildSuccess(ResultEnum.OK,"获取权限列表成功",result);
    }

    /**
     * 修改角色权限
     * @param roleName
     * @param authId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseBean updateAuthByRoleId(String roleName, String authId) {

        //获取角色Id
        Roles role = rolesDao.getRoleByRoleName(roleName);
        if (role == null){
            return ResultInfoUtil.buildError(ResultEnum.BAD_REQUEST, "该角色不存在");
        }
        Integer roleId = role.getRoleId();
        String[] authStr = authId.split(",");
        Integer[] authIds = new Integer[authStr.length];
        for (int i = 0; i < authStr.length; i++){
            authIds[i] = Integer.parseInt(authStr[i]);
            System.out.println(authIds[i]);
        }

        //先删除角色的所有权限
        authRoleDao.deleteAllAuthByRoleId(roleId);
        //给角色赋权
        // authId roleId
        for (int i = 0; i < authIds.length; i++){
            //对于每个权限
            //判断权限是否存在
            Auth auth = authDao.getAuthByAuthId(authIds[i]);
            System.out.println(auth);
            if (auth != null && auth.getPid() != 0 && exist(authIds,auth.getPid()) ){
                //权限的pid是否也存在auths
                System.out.println("插入了："+auth.getAuthId());
                authRoleDao.addAuth(authIds[i], roleId);
            }else if (auth != null && auth.getPid() == 0){
                System.out.println("插入了："+auth.getAuthId());
                authRoleDao.addAuth(authIds[i], roleId);
            }else {
                return ResultInfoUtil.buildError(ResultEnum.BAD_REQUEST,"存在权限不符合要求，请检查后再进行修改");
            }
            //不符合要求 则不进行添加
        }
        //获取修改后的权限列表
        List<Auth> result = getAuthListByRoleId(roleId);
        return ResultInfoUtil.buildSuccess(ResultEnum.OK,"修改权限列表成功",result);
    }

    /**
     * 判断权限的pid是否存在
     * @param authIds
     * @param authId
     * @return
     */
    public boolean exist(Integer[] authIds, Integer authId){
        //判断authId 是否存在于 authIds
        for(int i = 0 ;i < authIds.length; i++){
            if (authIds[i].equals(authId)){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取权限列表 通过roleId
     * @param roleId
     * @return
     */
    private List<Auth> getAuthListByRoleId(Integer roleId){
        //存贮角色拥有的权限
        List<Auth> authListHave = authRoleDao.getAllauthByRoleId(roleId);
        //获取所有权限
        List<Auth> result;
        //获取所有一级权限
        Integer id = null;
        result = authRoleDao.getFirstAuths(id);
        //对该一级权限获取所有的二级权限
        for (int i = 0; i < result.size(); i++) {
            //判断该角色是否拥有该权限
            if (authListHave.contains(result.get(i))){
                result.get(i).setHave(1);
            }
            //填写该一级权限的所有二级权限
            Integer pidFirst = result.get(i).getAuthId();
            List<Auth> second = authRoleDao.getAuthByPid(pidFirst, id);
            //填写该二级权限
            for (int j = 0; j < second.size(); j++) {
                //判断该角色是否拥有该权限
                if (authListHave.contains(second.get(j))){
                    second.get(j).setHave(1);
                }
                //获取该pid对应的子权限
                Integer pidSecond = second.get(j).getAuthId();
                List<Auth> third = authRoleDao.getAuthByPid(pidSecond, id);
                //填写三级权限
                for (int k = 0; k < third.size(); k++) {
                    //判断该角色是否拥有该权限
                    if (authListHave.contains(third.get(k))){
                        third.get(k).setHave(1);
                    }
                }
                second.get(j).setAuths(third);
            }
            result.get(i).setAuths(second);
        }
        return result;
    }

    /**
     * 通过authId roleId 删除用户权限
     * @param roleName
     * @param authId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean deleteAuthByRoleIdAuthId(String roleName, Integer authId) {
        System.out.println(roleName+ " : " + authId);
        //获取roleId
        Integer roleId = rolesDao.getRoleByRoleName(roleName).getRoleId();
        if (roleId == null){
            System.out.println("deleteAuthByRoleIdAuthId 角色不存在");
            ResultInfoUtil.buildError(ResultEnum.BAD_REQUEST,"角色不存在");
        }
        //查找该权限是否为三级权限
        Auth auth = authDao.getAuthByAuthId(authId);
        Integer pid = auth.getPid();
        Integer is_menu = auth.getIsMenu();
        if (is_menu == 0){
            //为三级权限
            //直接删除
            System.out.println("开始删除三级");
            authRoleDao.deleteAuthByRoleIdAuthId(authId,roleId);
            System.out.println("直接删除三级");
        }else if (is_menu == 0 && pid != 0){
            //判断是二级权限
            System.out.println("判断为二级权限");
            deleteSecond(roleId,authId);
        }else{
            //判断是一级权限
            System.out.println("判断为一级权限");
            deleteFirst(roleId,authId);
        }
        System.out.println("返回code");
        return ResultInfoUtil.buildSuccess(ResultEnum.OK, "删除权限成功",null);
    }

    /**
     * 删除一级权限及下面的子权限
     * @param roleId
     * @param authId
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteFirst(Integer roleId, Integer authId){
        System.out.println("开始删除一级权限");
        //依次先删除一级权限下的所有权限，再删除该一级权限
        List<Auth> secondList = authRoleDao.getAuthByPid(authId,roleId);
        for (int i = 0; i < secondList.size(); i++){
            //获取该二级权限下的三级权限
            Integer secondPid = secondList.get(i).getAuthId();
            List<Auth> thirdList = authRoleDao.getThirdAuthByAuthIdAndByRoleId(roleId,secondPid);
            for (int j = 0; j < thirdList.size(); j++) {
                //依次删除三级权限
                authRoleDao.deleteAuthByRoleIdAuthId(thirdList.get(j).getAuthId(), roleId);
            }
            //删除该二级权限
            authRoleDao.deleteAuthByRoleIdAuthId(secondList.get(i).getAuthId(), roleId);
        }
        //删除该三级权限
        authRoleDao.deleteAuthByRoleIdAuthId(authId, roleId);
        System.out.println("删除一级权限成功");
    }

    /**
     * 删除二级权限及下面的子权限
     * @param roleId
     * @param authId
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteSecond(Integer roleId, Integer authId){
        //依次先删除二级权限下的所有权限，再删除该二级权限
        //找出该二级权限下的所有三级权限
        System.out.println("开始删除二级权限");
        List<Auth> thirdList = authRoleDao.getThirdAuthByAuthIdAndByRoleId(roleId,authId);
        //依次删除三级权限
        for (int i = 0; i < thirdList.size(); i++){
            authRoleDao.deleteAuthByRoleIdAuthId(thirdList.get(i).getAuthId(),roleId);
        }
        //删除该二级权限
        authRoleDao.deleteAuthByRoleIdAuthId(authId,roleId);
        System.out.println("删除二级权限成功");
    }

    @Override
    public ResponseBean getMenu(String csPhone) {
        //获取用户身份
        List<Roles> csRole = csRoleDao.getRolesByCsPhone(csPhone);
        System.out.println(csRole);
        if (csRole != null){
            //权限菜单结果
            List<Auth> authMenuList = new ArrayList<>();
            for (int i = 0; i < csRole.size(); i++){
                Integer roleId = csRole.get(i).getRoleId();
                System.out.println(roleId);
                //获取所有一级权限
                int start = authMenuList.size();
                List<Auth> authList = authRoleDao.getFirstAuths(roleId);
                for (int k = 0; k < authList.size(); k++){
                    authMenuList.add(authList.get(k));
                }
                System.out.println(authMenuList);
                //对该一级权限获取所有的二级权限
                for (int j = 0; j < authList.size(); j++) {
                    //填写该一级权限的所有二级权限
                    Integer pidFirst = authMenuList.get(start).getAuthId();
                    List<Auth> second = authRoleDao.getAuthByPid(pidFirst, roleId);
                    System.out.println(second);
                    authMenuList.get(start).setAuths(second);
                }
            }
            System.out.println(authMenuList);
            return ResultInfoUtil.buildSuccess(ResultEnum.OK,"获取权限菜单成功",authMenuList);
        }
        return ResultInfoUtil.buildError(ResultEnum.INVALID_REQUEST,"获取权限菜单失败");
    }
}
